<!-- 新增编辑租机订单信息 -->
<template>
  <div class="container" v-loading="loading">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="150px" :validate-on-rule-change="false">
      <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="下单平台：" prop="platform">
            <el-select v-model.trim="form.platform" placeholder="请选择下单平台" @change="handleChangePlatform">
              <el-option v-for="item in selectPlatformType" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品分类：" prop="cat_id1">
            <el-select v-model.trim="form.cat_id1" placeholder="商品分类" class="" @change="handleChangeCat">
              <el-option v-for="item in category1List" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机品牌：" prop="brand">
            <el-select v-model.trim="form.brand" placeholder="手机品牌" class="" @change="handleChangeBrand">
              <el-option v-for="item in brandList" :label="item.cat_name" :value="item.cat_id" :key="item.cat_id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机型号：" prop="goods_id">
            <el-select v-model.trim="form.goods_id" placeholder="手机型号" filterable class="" @change="handleChangeGoods">
              <el-option v-for="item in goodsList" :label="item.goods_name" :value="item.goods_id" :key="item.goods_id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="租赁模式：" prop="order_rent_type_id">
            <el-select v-model.trim="form.order_rent_type_id" placeholder="租赁模式" filterable class="" @change="handleChangeOrderRentType">
              <el-option v-for="item in orderRentTypeList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机内存：" prop="sku_key">
            <el-select v-model.trim="form.sku_key" placeholder="手机内存" filterable class="" @change="handleChangeSkuKey">
              <el-option v-for="item in skuKeyList" :label="item.key_name" :value="item.key" :key="item.key"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="rentMode2">
          <el-form-item label="买断价：" prop="goods_price">
            <el-input v-model.trim="form.goods_price" @input="debounceHandleInputGoodsPrice" @change="handleChangeGoodsPrice" placeholder="买断价"><template v-slot:append>元</template></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="rentMode2">
          <el-form-item label="首付金额：" prop="advance_price">
            <el-input v-model.trim="form.advance_price" @change="handleChangeGoodsPrice" placeholder="首付金额"> <template v-slot:append>元</template></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="rentMode1">
          <el-form-item label="零售价：" prop="goods_price">
            <el-input v-model.trim="form.goods_price" @input="debounceHandleInputGoodsPrice" placeholder="零售价"><template v-slot:append>元</template></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="下单人姓名：" prop="name">
            <el-input v-model.trim="form.name" placeholder="下单人姓名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机号：" prop="mobile">
            <el-input v-model.trim="form.mobile" placeholder="手机号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="身份证号：" prop="id_number">
            <el-input v-model.trim="form.id_number" placeholder="身份证号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="订单生成日期：" prop="deduction_data">
            <el-date-picker v-model="form.deduction_data" type="date" value-format="X" placeholder="订单生成日期" @change="handleDateChange"> </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" v-if="!storePlatformList.includes(form.platform)">
        <el-col :span="6">
          <el-form-item label="省：" prop="province">
            <el-select v-model.trim="form.province" placeholder="请选择省" clearable @change="handleChangeProvince">
              <el-option v-for="item in provinceList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="市：" prop="city">
            <el-select v-model.trim="form.city" placeholder="请选择市" clearable @change="handleChangeCity">
              <el-option v-for="item in cityList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="县：" prop="district">
            <el-select v-model.trim="form.district" placeholder="请选择县" clearable>
              <el-option v-for="item in districtList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" v-if="storePlatformList.includes(form.platform)">
        <el-col :span="6">
          <el-form-item label="抖音(快手，美团)小店订单号：" prop="out_bill_no">
            <el-input v-model.trim="form.out_bill_no" placeholder="抖音(快手，美团)小店订单号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="绑定店铺：" prop="bind_store_id">
            <el-select v-model.trim="form.bind_store_id" placeholder="请选择绑定店铺">
              <el-option v-for="item in selectStoreList" :label="item.store_name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="详细地址：" prop="address">
            <el-input v-model.trim="form.address" type="textarea" placeholder="详细地址"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户备注：" prop="user_note">
            <el-input v-model.trim="form.user_note" type="textarea" placeholder="用户备注"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="平台备注：" prop="admin_note">
            <el-input v-model.trim="form.admin_note" type="textarea" placeholder="平台备注"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" v-if="methodType !== 'POST'">
        <el-col :span="6">
          <el-form-item label="订单号：" prop="order_sn">
            <el-input v-model.trim="form.order_sn" disabled placeholder="订单号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-divider content-position="left" v-if="billsList.length > 0"><span class="title-left-color">账单信息</span></el-divider>
    <BillsList :tableList="billsList" />
    <el-divider content-position="left" v-if="form.store.store_name !== ''"><span class="title-left-color">手机来源</span></el-divider>
    <div style="margin: 0 70px" v-if="form.store.store_name !== ''">
      <el-descriptions :column="4" size="default">
        <el-descriptions-item label="店铺:">{{ form.store.store_name }} {{ form.store.store_phone }}</el-descriptions-item>
        <el-descriptions-item label="c端用户:">{{ form.publish_user?.mobile }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <el-divider content-position="left" v-if="form.bindStore.store_name !== ''"><span class="title-left-color">绑定店铺、业务员信息</span></el-divider>
    <div style="margin: 0 70px" v-if="form.bindStore.store_name !== ''">
      <el-descriptions :column="4" size="default">
        <el-descriptions-item label="店铺名称:">{{ form.bindStore.store_name }}</el-descriptions-item>
        <el-descriptions-item label="手机号:">{{ form.bindStore.store_phone }}</el-descriptions-item>
        <el-descriptions-item label="业务员:">{{ form.bindStore.staff_name }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <el-divider content-position="left" v-if="orderActionList.length > 0"><span class="title-left-color">操作记录</span></el-divider>
    <OrderActionList :tableList="orderActionList" />
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import BillsList from "@/components/rentMachineManage/rentMachineOrderInfo/formtab/BillsList.vue";
import OrderActionList from "@/components/rentMachineManage/rentMachineOrderInfo/formtab/OrderActionList.vue";
import type {
  IOrderAction,
  IOrderRentType,
  IRentBill,
  IRentMachineOrderDetailVO,
  IRentMobileBrand,
  IRentMobileGoods,
  IRentMobileSpec,
  IRentRentOrderStore,
  ISearchPreRentBill,
  ISearchRentMobileBrand,
  ISearchRentMobileGoods,
  ISearchRentMobileSpec,
  ISearchRentOrderStore
} from "@/types/rentMachineManage/rentMachineOrderInfo";
import type { IDictData } from "@/types/dict";
import type { IRegion, ISearchRegion } from "@/types/redPacketMallManage/region";
import { getRentOrderStoreInfo } from "@/utils/api/admin/order/rentOrder";
import type { HasId, ViewMode } from "@/types/common";
import type { postOrPutType } from "@/constants";
import { commonRentMobileOrderInfo, getRentMobileCategoryInfo, getRentMobileOrderByIdInfo, getRentMobileOrderGoodsInfo, getRentMobileSpecInfo } from "@/utils/api/rentMobileOrder";
import { useState } from "@/hooks/useState";
import { getRegionInfo } from "@/utils/api/region";
import { debounce } from "@/utils/utils";
import { getPreBillListInfo } from "@/utils/api/installmentBill";
import { getGoodsCategoryList } from "@/utils/api/admin/goods/goodsCategory";
import type { IGoodsCategory, ISearchGoodsCategory } from "@/types/rentMachineManage/goodsCategory";
import { ElMessageBox, type FormRules } from "element-plus";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  id: number;
  provinceList: IRegion[];
  selectPlatformType: IDictData[];
}
const { id, provinceList, selectPlatformType } = defineProps<Props>();

const formStatus = defineModel<ViewMode>("formStatus", { required: true });

const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
}>();
/* 商品分类1 */
const category1List = ref<Array<IGoodsCategory>>([]);
/* 手机品牌 */
const brandList = ref<IRentMobileBrand[]>([]);
/* 手机型号 */
const goodsList = ref<IRentMobileGoods[]>([]);
/* 手机内存 */
const skuKeyList = ref<IRentMobileSpec[]>([]);
/* 市 */
const cityList = ref<Array<IRegion>>([]);
/* 区 */
const districtList = ref<Array<IRegion>>([]);

const rules = reactive<FormRules<IRentMachineOrderDetailVO>>({
  platform: [{ required: true, message: "请选择下单平台", trigger: "blur" }],
  cat_id1: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
  order_rent_type_id: [{ required: true, message: "请选择租赁模式", trigger: "blur" }],
  mobile: [{ required: true, message: "请填写手机号", trigger: "blur" }],
  id_number: [{ required: true, message: "请填写身份证号", trigger: "blur" }],
  name: [{ required: true, message: "请填写下单人姓名", trigger: "blur" }],
  issue: [{ required: true, message: "请填写扣款期数", trigger: "blur" }],
  goods_price: [{ required: true, message: "请填写买断价", trigger: "blur" }],
  advance_price: [{ required: true, message: "请填写首付金额", trigger: "blur" }],
  // province: [],
  // city: [],
  // district: [],
  address: [{ required: true, message: "请填写详细地址", trigger: "blur" }],
  brand: [{ required: true, message: "请选择手机品牌", trigger: "blur" }],
  goods_id: [{ required: true, message: "请选择手机型号", trigger: "blur" }],
  sku_key: [{ required: true, message: "请选择手机内存", trigger: "blur" }],
  deduction_data: [{ required: true, message: "请选择订单生成日期", trigger: "blur" }],
  stage_type: [{ required: true, message: "请选择押金月付", trigger: "blur" }]
});
/* 是否触发监听 */
const isWatch = ref(false);
const isDisabledbtn = ref(false);
const methodType = ref<postOrPutType>("PUT");
const formRef = useTemplateRef("formRef");
/* 租赁模式id */
const rentMode = ref<string | number>("");
/* 租赁模式 key */
const advance = ref<string | number>("");
/* 店铺列表的信息 */
const selectStoreList = ref<IRentRentOrderStore[]>([]);
const storePlatformList = ref<string[]>(["bytePlatform", "kuaishouStorePlatform", "taobaoPlatform", "weChatPlatform", "littleRedBookStorePlatform", "meituanStorePlatform"]);

/* 租赁模式列表 */
const orderRentTypeList = ref<IOrderRentType[]>([]);
/* 账单 */
const billsList = ref<IRentBill[]>([]);
/* 订单操作记录 */
const orderActionList = ref<IOrderAction[]>([]);

const form = reactive<IRentMachineOrderDetailVO>({
  id: 0,
  order_sn: "",
  brand_name: "",
  model_name: "",
  goods_name: "",
  sku_key_name: "",
  goods_price: "",
  total_amount: "",
  service_key_name: "",
  name: "",
  mobile: "",
  province_name: "",
  city_name: "",
  district_name: "",
  address: "",
  user_note: "",
  admin_note: "",
  fineness_name: "",
  bindStore: {
    staff_name: "",
    store_name: "",
    store_phone: "",
    store_id: 0
  },
  order_action: [],
  create_time: 0,
  pay_time: 0,
  cancel_time: 0,
  shipping_time: 0,
  platform_name: "",
  issue: 5,
  id_number: "",
  cat_id: "",
  cat_id1: "",
  cat_id2: 0,
  store_cat_id: 0,
  store_cat_id1: 0,
  store_cat_id2: 0,
  goods_id: "",
  sku_key: "",
  province: "",
  city: "",
  district: "",
  platform: "",
  platform_approval_status: "",
  rent_mobile_order_type: "",
  advance_price: "",
  store: {
    store_name: "",
    store_phone: ""
  },
  confirm_time: 0,
  order_rent_type_id: "",
  order_rent_type: {
    id: 0,
    name: "",
    is_advance: 0
  },
  is_recovery: 0,
  douyin_order_cps: null,
  master_name: "",
  card_contract_package_name: "",
  deposit_price: "",
  subsidy_price: "",
  promoter_user_mobile: "",
  fineness: "",
  is_guest_publish: 0,
  publish_user: {
    mobile: ""
  },
  stage_type: "",
  stage_type_name: "",
  is_receipt_signed: 0,
  bills: [],
  deduction_data: 0,
  order_receipt_esign: null,
  out_bill_no: "",
  brand: "",
  bind_store_id: ""
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
    form.deduction_data = parseInt(new Date().getTime() / 1000 + "");
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
/*  */
watch(
  () => id,
  newValue => {
    if (newValue == 0) {
      /* 初始化数据 */
      handleInitData();
    } else {
      if (["add", "edit"].includes(formStatus.value)) {
        form.id = newValue;
        handleGetMallOrderByIdInfo(id);
      }
    }
  }
);
/* 监听表单中某些字段，获取账单列表 */
watch([() => form.advance_price, () => form.deduction_data, () => form.sku_key, () => form.issue, () => form.order_rent_type_id, () => form.stage_type], () => {
  if (handleWatchRentMachineOrderFormStats()) {
    handleGetPreBillListInfo();
  }
});
/* 租赁手机相关模式 */
const rentMode2 = computed(() => {
  return [13, 14, 15, 22, 28].includes(+rentMode.value);
});
/* 共享手机模式 29 删除 */
const rentMode1 = computed(() => {
  return [30].includes(+rentMode.value);
});
const debounceHandleInputGoodsPrice = debounce(handleInputGoodsPrice, 1000);

/* 买断价输入事件 */
function handleInputGoodsPrice() {
  if (handleWatchRentMachineOrderFormStats()) {
    handleGetPreBillListInfo();
  }
}
/* 获取账单列表预览 */
function handleGetPreBillListInfo() {
  getPreBillListInfo<IRentBill[], ISearchPreRentBill>({
    goods_id: +form.goods_id,
    sku_key: form.sku_key,
    goods_price: form.goods_price,
    advance_price: form.advance_price,
    deduction_data: +form.deduction_data,
    order_rent_type_id: +form.order_rent_type_id,
    stage_type: form.stage_type
  })
    .then(res => {
      res.result.forEach(item => {
        item.tradeLog = { type_name: "" };
      });
      billsList.value = res.result;
    })
    .catch(() => {});
}

/* 监听多个字段 */
function handleWatchRentMachineOrderFormStats() {
  if (rentMode2.value) {
    return handleWatchRentMode2();
  } else if (rentMode1.value) {
    return handleWatchRentMode1();
  }
  return false;
}

/* 监听下单平台（租赁模式） */
function handleWatchRentMode2() {
  if (
    form.goods_id === "" ||
    form.deduction_data === "" ||
    form.goods_price === "" ||
    form.goods_price === null ||
    form.advance_price === "" ||
    form.advance_price === null ||
    form.sku_key === "" ||
    // form.issue === '' ||
    form.order_rent_type_id === "" ||
    isDisabledbtn.value ||
    !isWatch.value
  )
    return false;
  if (isNaN(+form.advance_price)) {
    ElMessage.warning("请填写正确的首付金额");
    return false;
  }
  if (Number(form.advance_price) > Number(form.goods_price)) {
    ElMessage.warning("首付金额需小于等于买断价");
    return false;
  }
  if (Number(form.advance_price) < 0) {
    ElMessage.warning("首付金额需大于0");
    return false;
  }
  return true;
}

/* 监听下单平台（共享模式） */
function handleWatchRentMode1() {
  if (
    form.goods_id === "" ||
    form.deduction_data === "" ||
    form.goods_price === "" ||
    form.goods_price === null ||
    form.sku_key === "" ||
    // form.issue === '' ||
    form.order_rent_type_id === "" ||
    form.stage_type === "" ||
    isDisabledbtn.value ||
    !isWatch.value
  )
    return false;
  if (Number(form.goods_price) < 0) {
    ElMessage.warning("零售价需大于0");
    return false;
  }
  return true;
}

/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;
  isWatch.value = false;
  form.id = 0;
  rentMode.value = "";
  form.order_sn = "";
  form.brand_name = "";
  form.model_name = "";
  form.cat_id = "";
  form.cat_id1 = "";
  form.goods_name = "";
  form.goods_id = "";
  form.brand = "";
  form.order_rent_type_id = "";
  form.sku_key = "";

  form.sku_key_name = "";
  form.goods_price = "";
  form.advance_price = "";
  form.issue = 5;
  form.total_amount = "";
  form.service_key_name = "";
  form.name = "";
  form.mobile = "";
  form.province = "";
  form.city = "";
  form.district = "";
  form.province_name = "";
  form.city_name = "";
  form.district_name = "";
  form.address = "";
  form.user_note = "";
  form.admin_note = "";
  form.fineness_name = "";
  form.bindStore.staff_name = "";
  form.bindStore.store_name = "";
  form.bindStore.store_phone = "";

  form.store.store_name = "";
  form.store.store_phone = "";

  form.publish_user = null;

  form.order_action = [];
  form.create_time = 0;
  form.pay_time = 0;
  form.cancel_time = 0;
  form.shipping_time = 0;
  form.platform_name = "";

  billsList.value = [];
  orderActionList.value = [];
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}

/* 获取订单详情数据 */
function handleGetMallOrderByIdInfo(id: number) {
  toggleState(true);
  getRentMobileOrderByIdInfo<IRentMachineOrderDetailVO, HasId>({ id })
    .then(res => {
      isWatch.value = false;
      rentMode.value = res.result.order_rent_type.is_advance;
      form.id = res.result.id;
      form.cat_id1 = res.result.cat_id1;
      form.order_sn = res.result.order_sn;
      handleGetRentMobileCategoryInfo(+form.cat_id1);
      form.platform = res.result.platform;
      form.platform_name = res.result.platform_name;
      handleChangePlatform();
      form.mobile = res.result.mobile;
      form.id_number = res.result.id_number;
      form.name = res.result.name;
      form.issue = res.result.issue;

      form.province = res.result.province;
      form.province_name = res.result.province_name;
      form.city = res.result.city;
      form.city_name = res.result.city_name;
      form.district = res.result.district;
      form.district_name = res.result.district_name;
      form.address = res.result.address;
      form.user_note = res.result.user_note;
      form.admin_note = res.result.admin_note;

      form.brand = res.result.store_cat_id;
      form.brand_name = res.result.brand_name;
      form.goods_id = res.result.goods_id;
      form.model_name = res.result.model_name;

      if (res.result.order_rent_type) {
        form.order_rent_type_id = res.result.order_rent_type.id;
        form.order_rent_type.name = res.result.order_rent_type.name;
        advance.value = res.result.order_rent_type.is_advance;
      }
      form.total_amount = res.result.total_amount;
      form.sku_key = res.result.sku_key;
      form.sku_key_name = res.result.sku_key_name;
      form.fineness_name = res.result.fineness_name;
      form.goods_price = res.result.goods_price;

      if (rentMode1.value) {
        form.goods_price = res.result.goods_price;
      } else if (rentMode2.value) {
        form.goods_price = res.result.total_amount;
      } else {
        form.goods_price = res.result.total_amount;
      }

      form.advance_price = res.result.advance_price;
      form.master_name = res.result.master_name;
      form.promoter_user_mobile = res.result.promoter_user_mobile;
      form.deposit_price = res.result.deposit_price;
      form.subsidy_price = res.result.subsidy_price;
      form.stage_type = res.result.stage_type;
      form.stage_type_name = res.result.stage_type_name;
      form.confirm_time = res.result.confirm_time;

      if (["douyinStore", "kuaishouStore", "kuaishouStoreRent", "taobao", "wechat", "meituanStore"].includes(res.result.bills[0].pay_source)) {
        form.out_bill_no = res.result.bills[0].out_bill_no;
      }
      form.create_time = res.result.create_time;
      form.deduction_data = res.result.deduction_data;

      if (res.result.douyin_order_cps !== null) {
        form.douyin_order_cps = res.result.douyin_order_cps;
      }

      if (res.result.bindStore !== null) {
        form.bind_store_id = res.result.bindStore.store_id;
        form.bindStore.store_name = res.result.bindStore.store_name;
        form.bindStore.store_phone = res.result.bindStore.store_phone;
        form.bindStore.staff_name = res.result.bindStore.staff_name;
      }
      if (res.result.store !== null) {
        form.store.store_name = res.result.store.store_name;
        form.store.store_phone = res.result.store.store_phone;
      }
      if (res.result.publish_user !== null) {
        form.publish_user!.mobile = res.result.publish_user.mobile;
      }

      handleGetRentMobileOrderGoodsInfo();
      handleGetRentMobileSpecInfo();

      form.service_key_name = res.result.service_key_name;

      form.bindStore = res.result.bindStore;
      form.create_time = res.result.create_time;
      form.pay_time = res.result.pay_time;
      form.cancel_time = res.result.cancel_time;
      form.shipping_time = res.result.shipping_time;

      /* 市县 获取 */
      handleGetRegionInfo(+form.province, cityList);
      handleGetRegionInfo(+form.province, districtList);
      billsList.value = res.result.bills;
      orderActionList.value = res.result.order_action;
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
      isWatch.value = true;
    });
}
/* 获取商品分类 */
function handleGetGoodsCategoryList(parent_id: number, level: number, categoryList: Ref<IGoodsCategory[]>) {
  getGoodsCategoryList<IGoodsCategory[], ISearchGoodsCategory>({
    parent_id,
    level
  })
    .then(res => {
      if (level === 1) {
        let result = res.result.filter(item => {
          /* 638（租赁手机） 639（二手机）  9（精品手机）不显示 */
          return [638].includes(item.id);
        });
        categoryList.value = result;
      } else {
        categoryList.value = res.result;
      }
    })
    .catch(() => {});
}
/* 获取手机品牌信息 */
function handleGetRentMobileCategoryInfo(cat_id1: number) {
  getRentMobileCategoryInfo<Array<IRentMobileBrand>, ISearchRentMobileBrand>({ cat_id1 })
    .then(res => {
      brandList.value = res.result;
    })
    .catch(() => {});
}
/* 获取手机型号信息（目前取的是 本店分类下 租赁手机下的 的品牌） */
function handleGetRentMobileOrderGoodsInfo() {
  getRentMobileOrderGoodsInfo<Array<IRentMobileGoods>, ISearchRentMobileGoods>({
    cat_id1: +form.cat_id1,
    cat_id: +form.brand,
    platform: form.platform
  })
    .then(res => {
      goodsList.value = res.result;
      if (form.goods_id !== "") {
        const data = goodsList.value.find(item => item.goods_id == form.goods_id);
        if (data) {
          handleFilterRentType(data.goods_id);
        }
      }
    })
    .catch(() => {});
}
/* 获取手机型号信息（目前取的是 本店分类下 租赁手机下的 的品牌） */
function handleGetRentMobileSpecInfo() {
  getRentMobileSpecInfo<Array<IRentMobileSpec>, ISearchRentMobileSpec>({
    goods_id: +form.goods_id,
    order_rent_type_id: +form.order_rent_type_id
  })
    .then(res => {
      skuKeyList.value = res.result;
    })
    .catch(() => {});
}

/* 获取省市县信息 */
function handleGetRegionInfo(parent_id: number, list: Ref<IRegion[]>) {
  getRegionInfo<IRegion, ISearchRegion>({ parent_id })
    .then(res => {
      list.value = ([] as IRegion[]).concat(res.result);
    })
    .catch(() => {});
}

/* 选择商品分类 */
function handleChangeCat() {
  form.brand = "";
  form.goods_id = "";
  form.sku_key = "";
  form.order_rent_type_id = "";
  brandList.value = [];
  goodsList.value = [];
  skuKeyList.value = [];
  orderRentTypeList.value = [];
  billsList.value = [];
  rentMode.value = "";
  form.stage_type = "";
  handleGetRentMobileCategoryInfo(+form.cat_id1);
}
/* 选择品牌 */
function handleChangeBrand() {
  /* 选择品牌后，重新获取型号信息 */
  form.goods_id = "";
  form.sku_key = "";
  form.order_rent_type_id = "";
  goodsList.value = [];
  skuKeyList.value = [];
  orderRentTypeList.value = [];
  billsList.value = [];
  rentMode.value = "";
  form.stage_type = "";
  if (form.platform == "") {
    ElMessage.warning("请先选择下单平台");
    form.brand = "";
    return;
  }
  handleGetRentMobileOrderGoodsInfo();
}
/* 选择型号 */
function handleChangeGoods(data: number) {
  /* 选择型号后，重新获取内存信息 */
  form.sku_key = "";
  form.order_rent_type_id = "";
  skuKeyList.value = [];
  orderRentTypeList.value = [];
  billsList.value = [];
  rentMode.value = "";
  form.stage_type = "";
  handleFilterRentType(data);
}
/* 选择内存 */
function handleChangeSkuKey(data: string) {
  /* 自动赋值 买断价和首付 */
  const item = skuKeyList.value.find(item => item.key === data);
  if (!item) return;
  /* 通过商品ID获取对应的租赁模式 */
  form.goods_price = item.retail_price;
  form.advance_price = item.advance;

  isWatch.value = true;
  handleVerifyGoodsPrice(item, handleResultIssue());
}
/* 通过模式返回剩余期数 */
function handleResultIssue() {
  const item = goodsList.value.find(item => item.goods_id == form.goods_id);
  if (!item) return 5;
  if (item.orderRentType == null) return 5;
  if (item.orderRentType.is_advance == 14) {
    return 12;
  } else if ([13].includes(item.orderRentType.is_advance)) {
    return 5;
  } else {
    return 5;
  }
}

/* 校验租机价/5期的值和填写的价格是否相同 */
function handleVerifyGoodsPrice(item: IRentMobileSpec, issue: number) {
  if (item && Number(item.month_price) !== 0 && Number(form.goods_price) !== 0 && Number(form.advance_price) !== 0) {
    /* 有一点误差也没事，也算是合理的价格，因为有除不尽的情况 */
    const isPricCorrect = Math.abs(Number(item.month_price) * issue + Number(form.advance_price) - Number(form.goods_price)) < 2;

    if (!isPricCorrect) {
      ElMessageBox.alert(`月供金额与系统设定金额不符，需注意是否填写错误!`, "再次确认租机价格", {
        confirmButtonText: "知道了"
      });
    }
  }
}
/* 填写买断价 */
function handleChangeGoodsPrice() {
  const item = skuKeyList.value.find(item => item.key === form.sku_key);
  if (!item) return;
  handleVerifyGoodsPrice(item, handleResultIssue());
}
/* 修改订单生成日期 */
function handleDateChange() {
  isWatch.value = true;
}

/* 过滤全款模式(共享手机的分期的也先过滤掉) */
function handleFilterRentType(data: number) {
  orderRentTypeList.value = goodsList.value.find(item => item.goods_id == data)!.orderRentTypes.filter(_item => ![24, 25, 19].includes(_item.is_advance));
}

/* 选择租赁模式 */
function handleChangeOrderRentType(data: number) {
  const item = orderRentTypeList.value.find(item => item.id == data);
  if (!item) return;
  rentMode.value = item.is_advance;
  form.stage_type = "";
  handleGetRentMobileSpecInfo();
}

/* 选择省 */
function handleChangeProvince() {
  cityList.value = [];
  districtList.value = [];
  form.city = "";
  form.district = "";
  handleGetRegionInfo(+form.province, cityList);
}
/* 选择市 */
function handleChangeCity() {
  districtList.value = [];
  form.district = "";
  handleGetRegionInfo(+form.province, districtList);
}

/* 保存校验数据 */
function handleValidate() {
  return true;
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    if (!handleValidate()) return;
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonRentMobileOrderInfo(form, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      emit("handleSuccess");
      cancelSubmit();
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  emit("handleInitData");
}

/* 根据对应平台获取店铺信息 */
function handleGetRentOrderStoreInfo() {
  getRentOrderStoreInfo<Array<IRentRentOrderStore>, ISearchRentOrderStore>({
    platform: form.platform
  })
    .then(res => {
      selectStoreList.value = res.result;
    })
    .catch(() => {});
}

/* 修改下单平台事件  */
function handleChangePlatform() {
  if (storePlatformList.value.includes(form.platform)) {
    // rules.province = [];
    // rules.city = [];
    // rules.district = [];
    form.bind_store_id = "";
    rules.bind_store_id = [{ required: true, message: "请选择绑定的店铺", trigger: "blur" }];
  } else {
    rules.bind_store_id = [];
    // rules.province = [{ required: true, message: "请选择省", trigger: "blur" }];
    // rules.city = [{ required: true, message: "请选择市", trigger: "blur" }];
    // rules.district = [{ required: true, message: "请选择县", trigger: "blur" }];
  }

  form.province = "";
  form.city = "";
  form.district = "";
  form.brand = "";
  form.goods_id = "";
  form.sku_key = "";
  goodsList.value = [];
  skuKeyList.value = [];
  billsList.value = [];
  handleGetRentOrderStoreInfo();
  nextTick(() => {
    formRef.value?.clearValidate();
  });
}
handleGetGoodsCategoryList(0, 1, category1List);
</script>

<style lang="scss" scoped>
/* layout-布局 */
.el-col {
  border-radius: 4px;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}
</style>
